/* eslint-disable no-unused-vars */
console.log('background !')

function getCurrentTab (callback) {
  let queryOptions = { active: true, lastFocusedWindow: true }
  chrome.tabs.query(queryOptions, ([tab]) => {
    if (chrome.runtime.lastError) { console.error(chrome.runtime.lastError) }
    // `tab` will either be a `tabs.Tab` instance or `undefined`.
    callback(tab)
  })
}

// background.js 或者 popup.js(browser action)
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  console.log('收到来自content-script的消息：')
  console.log(request, sender, sendResponse)
  if (request === 'closeCurrentTab') {
    chrome.tabs.remove(sender.tab.id, function () {})
    // getCurrentTab((tab) => {
    //   chrome.tabs.remove(tab.id, function () {})
    // })
  }
  if (request.type === 'tabs.create') {
    chrome.tabs.create({
      active: false,
      url: request.url
    }, function (tab) {
    //   console.log('创建tab结果：', tab)
    })
    // getCurrentTab((tab) => {
    //   chrome.tabs.remove(tab.id, function () {})
    // })
  }
  sendResponse('我是后台，我已收到你的消息：' + JSON.stringify(request))
})
